package orm

import (
	"gluenet/pkg/meta"
	"gluenet/pkg/ops/dbi"
)

const updateScheduleResult = `insert into schedule_result (instances_guid,instances_cells,schedule_map) values (?,?,?) on duplicate key update instances_cells=?,schedule_map=?`

func SaveScheduleResult(c dbi.GlueDB, res *meta.ScheduleResults) error {
	if _, err := c.MetaDB().Exec(updateScheduleResult, res.InstancesGuid, res.InstancesCells, res.ScheduleMap, res.InstancesCells, res.ScheduleMap); err != nil {
		return err
	}
	return nil
}

func SaveResourceTee(c dbi.GlueDB, root string, time string, tree string) error {
	if _, err := c.MetaDB().Exec(`insert into resource_tree (root,update_time,resource_tree) values (?,?,?) on duplicate key update update_time=?,resource_tree=?`, root, time, tree, time, tree); err != nil {
		return err
	}
	return nil
}

func SaveResourceDag(c dbi.GlueDB, root string, time string, dag string) error {
	if _, err := c.MetaDB().Exec(`insert into resource_dag (root,update_time,instances_dag) values (?, ?,?) on duplicate key update update_time=?,instances_dag=?`, root, time, dag, time, dag); err != nil {
		return err
	}
	return nil
}

const updateStrategyLinks = `insert into strategy_links(strategy_guid,application_guids) values(?,?) on duplicate key update application_guids=?`

func SaveStrategyLinks(c dbi.GlueDB, key string, appGuids string) error {
	if _, err := c.MetaDB().Exec(updateStrategyLinks, key, appGuids, appGuids); err != nil {
		return err
	}
	return nil
}

func PutInstanceRuntime(c dbi.GlueDB, ins *meta.InstanceRunTime) error {
	if _, err := c.MetaDB().Exec(`insert into instance_runtime(guid,platform,containers,containers_info) values(?,?,?,?) on duplicate key update platform=?,containers=?,containers_info=?`,
		ins.AppGuid, ins.AppPlatform, ins.Containers, ins.ContainersInfo, ins.AppPlatform, ins.Containers, ins.ContainersInfo); err != nil {
		return err
	}
	return nil
}

func PutAgentRuntime(c dbi.GlueDB, ags *meta.AgentRunTime) error {
	if _, err := c.MetaDB().Exec(`insert into agent_runtime(guid,platform,hosts,containers) values(?,?,?,?) on duplicate key update platform=?,hosts=?,containers=?`,
		ags.AgentGuid, ags.Platform, ags.Hosts, ags.Containers, ags.Platform, ags.Hosts, ags.Containers); err != nil {
		return err
	}
	return nil
}

func PutIndexs(c dbi.GlueDB, root string, indexs string) error {
	if _, err := c.MetaDB().Exec("insert into `index`(root,indexs) values(?,?) on duplicate key update indexs=?",
		root, indexs, indexs); err != nil {
		return err
	}
	return nil
}
